package com.yrxy.thread.interview.base;

/**
 * @author huanglaoxie(微信:yfct-8888)
 * @className WaitDemo
 * @description：wait使用方法示例
 * @date 2017/6/8 16:09
 */
public class WaitDemo {
    private final Object flag = new Object();
    public static void main(String[] args) {
        WaitDemo waitDemo = new WaitDemo();
        ThreadFirst threadFirst = waitDemo.new ThreadFirst();
        threadFirst.setName("奇数线程");
        threadFirst.start();
        ThreadSecond threadSecond = waitDemo.new ThreadSecond();
        threadSecond.setName("偶数线程");
        threadSecond.start();
    }

    class ThreadFirst extends Thread {
        @Override
        public void run() {
            synchronized (flag) {
                for (int i = 1; i <= 100; i += 2) {
                    flag.notify();
                    System.out.println("线程名称:"+Thread.currentThread().getName() +" , i  is ： "+i); // 奇数
                    try {
                        flag.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    class ThreadSecond extends Thread {
        @Override
        public void run() {
            synchronized (flag) {
                for (int i = 2; i <= 100; i += 2) {
                    flag.notify();
                    System.out.println("线程名称:"+Thread.currentThread().getName() +" , i  is ： "+i);  // 偶数
                    if (i == 100) {
                        // 当输出了最后一个数字的时候，不能再wait了
                        break;
                    }
                    try {
                        flag.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
